package com.my.bigsite.modules.act.web;

import java.io.ByteArrayInputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.my.bigsite.common.web.BaseController;
import com.my.bigsite.modules.act.service.ActModelService;
 

@Controller
@RequestMapping("${adminPath}/act/model")
public class ModuleController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(ModuleController.class);
	
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private ActModelService actModelService;
	
	/**
	 * 流程模型列表
	 */
	//@RequiresPermissions("act:model:edit")
	@RequestMapping(value = { "list", "" })
	public ModelAndView modelList(HttpServletRequest request, HttpServletResponse response) {
		/*	  String bpmnFileName = "act/leave-dynamic-from.bpmn";
	ProcessEngine processEngine = ProcessEngineConfiguration
                .createStandaloneInMemProcessEngineConfiguration()
                .buildProcessEngine();

        //RepositoryService repositoryService = processEngine.getRepositoryService();
        repositoryService
                .createDeployment()
                .addInputStream(
                        "leavefrom.bpmn",
                        this.getClass().getClassLoader()
                                .getResourceAsStream(bpmnFileName)).deploy();*/

		  List<Model> list = repositoryService.createModelQuery().list();  
		  logger.info("获取模型列表:", list.size()); 
		  ModelAndView view=new ModelAndView();
		 view.addObject("ModelList", list);
		 view.setViewName("modules/act/actModelList");
		 return view;
	}
	/** 
     * 创建模型 
     */  
	@RequestMapping(value = "create")
	  public void create(@RequestParam("name") String name, @RequestParam("key") String key, @RequestParam("description") String description,
	          HttpServletRequest request, HttpServletResponse response) {
	    try {
	      ObjectMapper objectMapper = new ObjectMapper();
	      ObjectNode editorNode = objectMapper.createObjectNode();
	      editorNode.put("id", "canvas");
	      editorNode.put("resourceId", "canvas");
	      ObjectNode stencilSetNode = objectMapper.createObjectNode();
	      stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
	      editorNode.put("stencilset", stencilSetNode);
	      Model modelData = repositoryService.newModel();
	 
	      ObjectNode modelObjectNode = objectMapper.createObjectNode();
	      modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
	      modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
	      description = StringUtils.defaultString(description);
	      modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
	      modelData.setMetaInfo(modelObjectNode.toString());
	      modelData.setName(name);
	      modelData.setKey(StringUtils.defaultString(key));
	 
	      repositoryService.saveModel(modelData);
	      repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
	 
	      response.sendRedirect(request.getContextPath() + "/static/act/modeler.html?modelId=" + modelData.getId());
	    } catch (Exception e) {
	      logger.error("创建模型失败:", e);
	    }
	  }
	
	
 
	
	/** 
     * 根据Model部署流程 
     */  
    @ResponseBody  
    @RequestMapping("deploy")  
    public String deploy(String id) {  
        //Json json = new Json();  
        try {  
            Model modelData = repositoryService.getModel(id);  
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));  
            byte[] bpmnBytes = null;  
  
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);  
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);  
  
            String processName = modelData.getName() + ".bpmn20.xml";  
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes)).deploy();  
           // json.setMsg("部署成功，部署ID=" + deployment.getId());  
            //json.setSuccess(true);  
        } catch (Exception e) {  
            logger.error("根据模型部署流程失败：modelId={}", id, e);  
            //json.setMsg("模型部署流程失败");  
        }  
        return "";  
    }  
    /** 
     * 导出model的xml文件 
     */  
    @RequestMapping("export")  
    public void export(String modelId, HttpServletResponse response) {  
        try {  
            Model modelData = repositoryService.getModel(modelId);  
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();  
            JsonNode editorNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));  
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);  
            BpmnXMLConverter xmlConverter = new BpmnXMLConverter();  
            byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);  
  
            ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);  
            IOUtils.copy(in, response.getOutputStream());  
            String filename = bpmnModel.getMainProcess().getId() + ".bpmn20.xml";  
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);  
            response.flushBuffer();  
        } catch (Exception e) {  
            logger.error("导出model的xml文件失败：modelId={}", modelId, e);  
        }  
    }  
    
    @RequestMapping(value = "delete")  
    public String delete(String id) {  
        repositoryService.deleteModel(id);  
        return "redirect:" + adminPath + "/act/model";
    }  
}
